#include <jni.h>
#include "com_rfid_jni_JNI_RFIDCaller.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* jstring2str(JNIEnv* env, jstring jstr)
{
       char* rtn = NULL;
       jclass clsstring = env->FindClass("java/lang/String");
       jstring strencode = env->NewStringUTF("utf-8");
       jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
       jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr, mid, strencode);
       jsize alen = env->GetArrayLength(barr);
       jbyte* ba = env->GetByteArrayElements(barr, JNI_FALSE);
       if (alen > 0)
       {
                 rtn = (char*)malloc(alen + 1);
                 memcpy(rtn, ba, alen);
                 rtn[alen] = 0;
       }
       env->ReleaseByteArrayElements(barr, ba, 0);
       return rtn;
}

jstring str2jstring(JNIEnv* env, const char* pat)
{
       jclass strClass = env->FindClass("Ljava/lang/String;");
       jmethodID ctorID = env->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
       jbyteArray bytes = env->NewByteArray(strlen(pat));
       env->SetByteArrayRegion(bytes, 0, strlen(pat), (jbyte*)pat);
       jstring encoding = env->NewStringUTF("utf-8");
       return (jstring)env->NewObject(strClass, ctorID, bytes, encoding);
} 


JNIEXPORT void JNICALL Java_com_rfid_jni_JNI_1RFIDCaller__1ring
(JNIEnv *env, jobject jobj)
{
	printf("ring once!");
}

JNIEXPORT jstring JNICALL Java_com_rfid_jni_JNI_1RFIDCaller__1read
(JNIEnv *env, jobject jobj, jint jareaCount, jint jareaStarts)
{
	jstring jdata;
	const char* data = "read data success!";
	jdata = str2jstring(env, data);
	return jdata;
}

JNIEXPORT void JNICALL Java_com_rfid_jni_JNI_1RFIDCaller__1write
(JNIEnv *env, jobject jobj, jint jareaCount, jint jareaStarts, jstring jdata)
{
	char* data = jstring2str(env, jdata);
	printf("write data to area[count:%d, start:%d]: %s", jareaCount, jareaStarts, data);
}